package com.zyy;

/**
 * @ProjectName: concurrent
 * @Package: com.zyy
 * @ClassName: EndRunnable
 * @Author: ZHAYUYAO
 * @Description: 如何安全中断Runnable线程
 * @Date: 2019/9/4 22:31
 * @Version: 1.0
 */
public class EndRunnable {
    static class MyRunnable implements Runnable {

        @Override
        public void run() {
            Thread currentThread = Thread.currentThread();
            //不能将下面循环中的currentThread.isInterrupted()提取到循环外面，不然中断不了
            while (!currentThread.isInterrupted()) {
                System.out.println(currentThread.getName() + " is running");
            }
            System.out.println(currentThread.getName() + " isInterrupted flag is " + currentThread.isInterrupted());

        }
    }

    public static void main(String[] args) {
        Thread thread = new Thread(new MyRunnable());
        thread.start();
        try {
            Thread.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread.interrupt();
    }
}
